Project 2: Breakout Strategy

Instructions

Each problem consists of a function to implement and instructions on how to implement the function. The parts of the function that need to be implemented are marked with a # TODO comment. After implementing the function, run the cell to test it against the unit tests we've provided. For each problem, we provide one or more unit tests from our project_tests package. These unit tests won't tell you if your answer is correct, but will warn you of any major errors. Your code will be checked for the correct solution when you submit it to Udacity.

Packages

When you implement the functions, you'll only need to you use the packages you've used in the classroom, like Pandas and Numpy. These packages will be imported for you. We recommend you don't add any import statements, otherwise the grader might not be able to run your code.

The other packages that we're importing are helper, project_helper, and project_tests. These are custom packages built to help you solve the problems. The helper and project_helper module contains utility functions and graph functions. The project_tests contains the unit tests for all the problems.

Install Packages

In [1]:
import sys
!{sys.executable} -m pip install -r requirements.txt
Requirement already satisfied: colour==0.1.5 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 1)) (0.1.5)
Requirement already satisfied: cvxpy==1.0.3 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 2)) (1.0.3)
Requirement already satisfied: cycler==0.10.0 in /opt/conda/lib/python3.6/site-packages/cycler-0.10.0-py3.6.egg (from -r requirements.txt (line 3)) (0.10.0)
Requirement already satisfied: numpy==1.13.3 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 4)) (1.13.3)
Requirement already satisfied: pandas==0.21.1 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 5)) (0.21.1)
Requirement already satisfied: plotly==2.2.3 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 6)) (2.2.3)
Requirement already satisfied: pyparsing==2.2.0 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 7)) (2.2.0)
Requirement already satisfied: python-dateutil==2.6.1 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 8)) (2.6.1)
Requirement already satisfied: pytz==2017.3 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 9)) (2017.3)
Requirement already satisfied: requests==2.18.4 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 10)) (2.18.4)
Requirement already satisfied: scipy==1.0.0 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 11)) (1.0.0)
Requirement already satisfied: scikit-learn==0.19.1 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 12)) (0.19.1)
Requirement already satisfied: six==1.11.0 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 13)) (1.11.0)
Requirement already satisfied: tqdm==4.19.5 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 14)) (4.19.5)
Requirement already satisfied: zipline==1.2.0 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 15)) (1.2.0)
Requirement already satisfied: fastcache in /opt/conda/lib/python3.6/site-packages (from cvxpy==1.0.3->-r requirements.txt (line 2)) (1.0.2)
Requirement already satisfied: scs>=1.1.3 in /opt/conda/lib/python3.6/site-packages (from cvxpy==1.0.3->-r requirements.txt (line 2)) (2.1.2)
Requirement already satisfied: ecos>=2 in /opt/conda/lib/python3.6/site-packages (from cvxpy==1.0.3->-r requirements.txt (line 2)) (2.0.7.post1)
Requirement already satisfied: toolz in /opt/conda/lib/python3.6/site-packages (from cvxpy==1.0.3->-r requirements.txt (line 2)) (0.8.2)
Requirement already satisfied: osqp in /opt/conda/lib/python3.6/site-packages (from cvxpy==1.0.3->-r requirements.txt (line 2)) (0.6.1)
Requirement already satisfied: multiprocess in /opt/conda/lib/python3.6/site-packages (from cvxpy==1.0.3->-r requirements.txt (line 2)) (0.70.10)
Requirement already satisfied: nbformat>=4.2 in /opt/conda/lib/python3.6/site-packages (from plotly==2.2.3->-r requirements.txt (line 6)) (4.4.0)
Requirement already satisfied: decorator>=4.0.6 in /opt/conda/lib/python3.6/site-packages (from plotly==2.2.3->-r requirements.txt (line 6)) (4.0.11)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.6/site-packages (from requests==2.18.4->-r requirements.txt (line 10)) (3.0.4)
Requirement already satisfied: idna<2.7,>=2.5 in /opt/conda/lib/python3.6/site-packages (from requests==2.18.4->-r requirements.txt (line 10)) (2.6)
Requirement already satisfied: urllib3<1.23,>=1.21.1 in /opt/conda/lib/python3.6/site-packages (from requests==2.18.4->-r requirements.txt (line 10)) (1.22)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.6/site-packages (from requests==2.18.4->-r requirements.txt (line 10)) (2019.11.28)
Requirement already satisfied: sqlalchemy>=1.0.8 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (1.1.13)
Requirement already satisfied: pandas-datareader<0.6,>=0.2.1 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (0.5.0)
Requirement already satisfied: MarkupSafe>=0.23 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (1.0)
Requirement already satisfied: sortedcontainers>=1.4.4 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (2.2.2)
Requirement already satisfied: bottleneck>=1.0.0 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (1.3.2)
Requirement already satisfied: tables>=3.3.0 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (3.6.1)
Requirement already satisfied: setuptools>18.0 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (38.4.0)
Requirement already satisfied: intervaltree>=2.1.0 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (3.1.0)
Requirement already satisfied: empyrical>=0.4.2 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (0.5.3)
Requirement already satisfied: networkx<2.0,>=1.9.1 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (1.11)
Requirement already satisfied: Mako>=1.0.1 in /opt/conda/lib/python3.6/site-packages/Mako-1.0.7-py3.6.egg (from zipline==1.2.0->-r requirements.txt (line 15)) (1.0.7)
Requirement already satisfied: bcolz<1,>=0.12.1 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (0.12.1)
Requirement already satisfied: Logbook>=0.12.5 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (1.5.3)
Requirement already satisfied: multipledispatch>=0.4.8 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (0.6.0)
Requirement already satisfied: statsmodels>=0.6.1 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (0.8.0)
Requirement already satisfied: contextlib2>=0.4.0 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (0.6.0.post1)
Requirement already satisfied: click>=4.0.0 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (6.7)
Requirement already satisfied: alembic>=0.7.7 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (1.4.2)
Requirement already satisfied: patsy>=0.4.0 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (0.4.1)
Requirement already satisfied: requests-file>=1.4.1 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (1.5.1)
Requirement already satisfied: numexpr>=2.6.1 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (2.6.4)
Requirement already satisfied: pip>=7.1.0 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (18.1)
Requirement already satisfied: lru-dict>=1.1.4 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (1.1.6)
Requirement already satisfied: Cython>=0.25.2 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (0.29.7)
Requirement already satisfied: cyordereddict>=0.2.2 in /opt/conda/lib/python3.6/site-packages (from zipline==1.2.0->-r requirements.txt (line 15)) (1.0.0)
Requirement already satisfied: future in /opt/conda/lib/python3.6/site-packages (from osqp->cvxpy==1.0.3->-r requirements.txt (line 2)) (0.16.0)
Requirement already satisfied: dill>=0.3.2 in /opt/conda/lib/python3.6/site-packages (from multiprocess->cvxpy==1.0.3->-r requirements.txt (line 2)) (0.3.2)
Requirement already satisfied: ipython-genutils in /opt/conda/lib/python3.6/site-packages (from nbformat>=4.2->plotly==2.2.3->-r requirements.txt (line 6)) (0.2.0)
Requirement already satisfied: traitlets>=4.1 in /opt/conda/lib/python3.6/site-packages (from nbformat>=4.2->plotly==2.2.3->-r requirements.txt (line 6)) (4.3.2)
Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /opt/conda/lib/python3.6/site-packages (from nbformat>=4.2->plotly==2.2.3->-r requirements.txt (line 6)) (2.6.0)
Requirement already satisfied: jupyter-core in /opt/conda/lib/python3.6/site-packages (from nbformat>=4.2->plotly==2.2.3->-r requirements.txt (line 6)) (4.4.0)
Requirement already satisfied: requests-ftp in /opt/conda/lib/python3.6/site-packages (from pandas-datareader<0.6,>=0.2.1->zipline==1.2.0->-r requirements.txt (line 15)) (0.3.1)
Requirement already satisfied: python-editor>=0.3 in /opt/conda/lib/python3.6/site-packages (from alembic>=0.7.7->zipline==1.2.0->-r requirements.txt (line 15)) (1.0.4)

Load Packages

In [2]:
import pandas as pd
import numpy as np
import helper
import project_helper
import project_tests

Market Data

Load Data

While using real data will give you hands on experience, it's doesn't cover all the topics we try to condense in one project. We'll solve this by creating new stocks. We've create a scenario where companies mining Terbium are making huge profits. All the companies in this sector of the market are made up. They represent a sector with large growth that will be used for demonstration latter in this project.

In [3]:
# Move data
# import shutil   
# shutil.copytree('/home/workspace/../../data/project_2', 'data')
In [4]:
# Load data
df_original = pd.read_csv('data/eod-quotemedia.csv', parse_dates=['date'], index_col=False)

# Add TB sector (Terbium stocks) to the market (for all dates)
df = df_original
df = pd.concat([df] + project_helper.generate_tb_sector(df[df['ticker'] == 'AAPL']['date']), ignore_index=True)

close = df.reset_index().pivot(index='date', columns='ticker', values='adj_close')
high = df.reset_index().pivot(index='date', columns='ticker', values='adj_high')
low = df.reset_index().pivot(index='date', columns='ticker', values='adj_low')

print('Loaded Data')
Loaded Data
In [5]:
df.head()
Out[5]:
adj_close adj_high adj_low adj_open date ticker
0 29.99418563 30.11804324 29.52627909 nan 2013-07-01 A
1 29.65013670 30.20061499 29.55380300 nan 2013-07-02 A
2 29.70518453 29.90473291 29.39554049 nan 2013-07-03 A
3 30.43456826 30.47929462 29.86344704 nan 2013-07-05 A
4 30.52402098 30.73733132 30.35887750 nan 2013-07-08 A

View Data

To see what one of these 2-d matrices looks like, let's take a look at the closing prices matrix.

In [6]:
close.head()
Out[6]:
ticker A AAL AAP AAPL ABBV ABC ABT ACN ADBE ADI ... XL XLNX XOM XRAY XRX XYL YUM ZBH ZION ZTS
date
2013-07-01 29.99418563 16.17609308 81.13821681 53.10917319 34.92447839 50.86319750 31.42538772 64.69409505 46.23500000 39.91336014 ... 27.66879066 35.28892781 76.32080247 40.02387348 22.10666494 25.75338607 45.48038323 71.89882693 27.85858718 29.44789315
2013-07-02 29.65013670 15.81983388 80.72207258 54.31224742 35.42807578 50.69676639 31.27288084 64.71204071 46.03000000 39.86057632 ... 27.54228410 35.05903252 76.60816761 39.96552964 22.08273998 25.61367511 45.40266113 72.93417195 28.03893238 28.57244125
2013-07-03 29.70518453 16.12794994 81.23729877 54.61204262 35.44486235 50.93716689 30.72565028 65.21451912 46.42000000 40.18607651 ... 27.33445191 35.28008569 76.65042719 40.00442554 22.20236479 25.73475794 46.06329899 72.30145844 28.18131017 28.16838652
2013-07-05 30.43456826 16.21460758 81.82188233 54.17338125 35.85613355 51.37173702 31.32670680 66.07591068 47.00000000 40.65233352 ... 27.69589920 35.80177117 77.39419581 40.67537968 22.58516418 26.06075017 46.41304845 73.16424628 29.39626730 29.02459772
2013-07-08 30.52402098 16.31089385 82.95141667 53.86579916 36.66188936 52.03746147 31.76628544 66.82065546 46.62500000 40.25645492 ... 27.98505704 35.20050655 77.96892611 40.64620776 22.48946433 26.22840332 46.95062632 73.89282298 29.57661249 29.76536472

5 rows × 519 columns

In [7]:
print(close.shape)
(1009, 519)

Stock Example

Let's see what a single stock looks like from the closing prices. For this example and future display examples in this project, we'll use Apple's stock (AAPL). If we tried to graph all the stocks, it would be too much information.

In [8]:
apple_ticker = 'AAPL'
project_helper.plot_stock(close[apple_ticker], '{} Stock'.format(apple_ticker))

The Alpha Research Process

In this project you will code and evaluate a "breakout" signal. It is important to understand where these steps fit in the alpha research workflow. The signal-to-noise ratio in trading signals is very low and, as such, it is very easy to fall into the trap of overfitting to noise. It is therefore inadvisable to jump right into signal coding. To help mitigate overfitting, it is best to start with a general observation and hypothesis; i.e., you should be able to answer the following question before you touch any data:

What feature of markets or investor behaviour would lead to a persistent anomaly that my signal will try to use?

Ideally the assumptions behind the hypothesis will be testable before you actually code and evaluate the signal itself. The workflow therefore is as follows:

image

In this project, we assume that the first three steps area done ("observe & research", "form hypothesis", "validate hypothesis"). The hypothesis you'll be using for this project is the following:

  • In the absence of news or significant investor trading interest, stocks oscillate in a range.
  • Traders seek to capitalize on this range-bound behaviour periodically by selling/shorting at the top of the range and buying/covering at the bottom of the range. This behaviour reinforces the existence of the range.
  • When stocks break out of the range, due to, e.g., a significant news release or from market pressure from a large investor:
    • the liquidity traders who have been providing liquidity at the bounds of the range seek to cover their positions to mitigate losses, thus magnifying the move out of the range, and
    • the move out of the range attracts other investor interest; these investors, due to the behavioural bias of herding (e.g., Herd Behavior) build positions which favor continuation of the trend.

Using this hypothesis, let start coding..

Compute the Highs and Lows in a Window

You'll use the price highs and lows as an indicator for the breakout strategy. In this section, implement get_high_lows_lookback to get the maximum high price and minimum low price over a window of days. The variable lookback_days contains the number of days to look in the past. Make sure this doesn't include the current day.

In [9]:
def get_high_lows_lookback(high, low, lookback_days):
    """
    Get the highs and lows in a lookback window.
    
    Parameters
    ----------
    high : DataFrame
        High price for each ticker and date
    low : DataFrame
        Low price for each ticker and date
    lookback_days : int
        The number of days to look back
    
    Returns
    -------
    lookback_high : DataFrame
        Lookback high price for each ticker and date
    lookback_low : DataFrame
        Lookback low price for each ticker and date
    """
    
    # TODO: Implement function
    lookback_high = high.rolling(lookback_days).max().shift(1) # Max of last `lookback_days`, excluding current day
    lookback_low = low.rolling(lookback_days).min().shift(1) # Min of last `lookback_days`, excluding current day
    
    return lookback_high, lookback_low


project_tests.test_get_high_lows_lookback(get_high_lows_lookback)
Tests Passed

View Data

Let's use your implementation of get_high_lows_lookback to get the highs and lows for the past 50 days and compare it to it their respective stock. Just like last time, we'll use Apple's stock as the example to look at.

In [10]:
lookback_days = 50
lookback_high, lookback_low = get_high_lows_lookback(high, low, lookback_days)
In [11]:
lookback_high.head()
Out[11]:
ticker A AAL AAP AAPL ABBV ABC ABT ACN ADBE ADI ... XL XLNX XOM XRAY XRX XYL YUM ZBH ZION ZTS
date
2013-07-01 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan
2013-07-02 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan
2013-07-03 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan
2013-07-05 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan
2013-07-08 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan

5 rows × 519 columns

In [12]:
lookback_high.tail()
Out[12]:
ticker A AAL AAP AAPL ABBV ABC ABT ACN ADBE ADI ... XL XLNX XOM XRAY XRX XYL YUM ZBH ZION ZTS
date
2017-06-26 60.46721832 51.50520667 151.31004484 154.23580350 71.25471927 95.96103830 48.61895833 126.10832371 147.45000000 88.15368471 ... 43.58273073 67.16177971 80.48150839 65.16409344 27.76307903 53.90920663 74.09922066 129.10303820 43.20525369 63.54989342
2017-06-27 60.46721832 51.50520667 151.31004484 154.23580350 71.25471927 95.96103830 48.61895833 126.10832371 147.45000000 88.15368471 ... 43.58273073 67.16177971 80.48150839 65.16409344 28.05995914 54.21567746 74.19746236 129.10303820 43.20525369 63.54989342
2017-06-28 60.46721832 51.50520667 151.31004484 154.23580350 71.25471927 95.96103830 48.61895833 126.10832371 147.45000000 88.15368471 ... 43.58273073 67.16177971 80.48150839 65.16409344 28.15572692 54.21567746 74.19746236 129.10303820 43.20525369 63.54989342
2017-06-29 60.46721832 51.50520667 151.31004484 154.23580350 71.25471927 95.96103830 48.61895833 126.10832371 147.45000000 88.15368471 ... 43.58273073 67.16177971 80.48150839 65.16409344 28.45399663 54.40351441 74.19746236 129.10303820 43.20525369 63.54989342
2017-06-30 60.46721832 51.50520667 151.31004484 154.23580350 71.25471927 96.13788879 48.61895833 126.10832371 147.45000000 88.15368471 ... 43.71019429 67.16177971 80.48150839 65.16409344 28.45399663 54.81873295 74.19746236 129.10303820 44.23089769 63.54989342

5 rows × 519 columns

In [13]:
project_helper.plot_high_low(
    close[apple_ticker],
    lookback_high[apple_ticker],
    lookback_low[apple_ticker],
    'High and Low of {} Stock'.format(apple_ticker))

Compute Long and Short Signals

Using the generated indicator of highs and lows, create long and short signals using a breakout strategy. Implement get_long_short to generate the following signals:

Signal Condition
-1 Low > Close Price
1 High < Close Price
0 Otherwise

In this chart, Close Price is the close parameter. Low and High are the values generated from get_high_lows_lookback, the lookback_high and lookback_low parameters.

In [14]:
def get_long_short(close, lookback_high, lookback_low):
    """
    Generate the signals long, short, and do nothing.
    
    Parameters
    ----------
    close : DataFrame
        Close price for each ticker and date
    lookback_high : DataFrame
        Lookback high price for each ticker and date
    lookback_low : DataFrame
        Lookback low price for each ticker and date
    
    Returns
    -------
    long_short : DataFrame
        The long, short, and do nothing signals for each ticker and date
    """
    
    # TODO: Implement function
    long_short = pd.DataFrame(0, index=close.index, columns=close.columns)    
    long_short[close > lookback_high] = 1 # Buy/Long
    long_short[close < lookback_low] = -1 # Sell/Short 
    
    return long_short


project_tests.test_get_long_short(get_long_short)
Tests Passed

View Data

Let's compare the signals you generated against the close prices. This chart will show a lot of signals. Too many in fact. We'll talk about filtering the redundant signals in the next problem.

In [15]:
signal = get_long_short(close, lookback_high, lookback_low)
In [16]:
signal.sample(5)
Out[16]:
ticker A AAL AAP AAPL ABBV ABC ABT ACN ADBE ADI ... XL XLNX XOM XRAY XRX XYL YUM ZBH ZION ZTS
date
2014-09-03 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 1 0 0 0 0 1
2017-04-18 0 0 0 0 0 -1 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
2013-10-09 0 0 0 0 0 0 0 0 0 0 ... 0 0 -1 0 0 0 -1 0 0 0
2014-01-02 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
2014-01-31 0 0 0 0 0 0 0 0 0 0 ... 0 0 -1 0 0 0 0 0 0 -1

5 rows × 519 columns

In [17]:
project_helper.plot_signal(
    close[apple_ticker],
    signal[apple_ticker],
    'Long and Short of {} Stock'.format(apple_ticker))

Filter Signals

That was a lot of repeated signals! If we're already shorting a stock, having an additional signal to short a stock isn't helpful for this strategy. This also applies to additional long signals when the last signal was long.

Implement filter_signals to filter out repeated long or short signals within the lookahead_days. If the previous signal was the same, change the signal to 0 (do nothing signal). For example, say you have a single stock time series that is

[1, 0, 1, 0, 1, 0, -1, -1]

Running filter_signals with a lookahead of 3 days should turn those signals into

[1, 0, 0, 0, 1, 0, -1, 0]

To help you implement the function, we have provided you with the clear_signals function. This will remove all signals within a window after the last signal. For example, say you're using a windows size of 3 with clear_signals. It would turn the Series of long signals

[0, 1, 0, 0, 1, 1, 0, 1, 0]

into

[0, 1, 0, 0, 0, 1, 0, 0, 0]

clear_signals only takes a Series of the same type of signals, where 1 is the signal and 0 is no signal. It can't take a mix of long and short signals. Using this function, implement filter_signals.

For implementing filter_signals, we don't reccommend you try to find a vectorized solution. Instead, you should use the iterrows over each column.

In [18]:
def clear_signals(signals, window_size):
    """
    Clear out signals in a Series of just long or short signals.
    
    Remove the number of signals down to 1 within the window size time period.
    
    Parameters
    ----------
    signals : Pandas Series
        The long, short, or do nothing signals
    window_size : int
        The number of days to have a single signal       
    
    Returns
    -------
    signals : Pandas Series
        Signals with the signals removed from the window size
    """
    # Start with buffer of window size
    # This handles the edge case of calculating past_signal in the beginning
    clean_signals = [0]*window_size
    
    for signal_i, current_signal in enumerate(signals):
        
        # Check if there was a signal in the past window_size of days
        has_past_signal = bool(sum(clean_signals[signal_i:signal_i+window_size]))
        
        # Use the current signal if there's no past signal, else 0/False
        clean_signals.append(not has_past_signal and current_signal)
        
    # Remove buffer
    clean_signals = clean_signals[window_size:]

    # Return the signals as a Series of Ints
    return pd.Series(np.array(clean_signals).astype(np.int), signals.index)


def filter_signals(signal, lookahead_days):
    """
    Filter out signals in a DataFrame.
    
    Parameters
    ----------
    signal : DataFrame
        The long, short, and do nothing signals for each ticker and date
    lookahead_days : int
        The number of days to look ahead
    
    Returns
    -------
    filtered_signal : DataFrame
        The filtered long, short, and do nothing signals for each ticker and date
    """
    
    # TODO: Implement function
    filtered_signal = pd.DataFrame(0, index=signal.index, columns=signal.columns) 
    
    # For each series 
    for column, series in signal.iteritems():
        
        signal_long = pd.Series(0, index=series.index) # Series of 0s with all days 
        signal_long[series==1] = 1 # Fill in 1s where original series is 1 
        signal_long = clear_signals(signal_long, lookahead_days) # Remove excess signals 
        
        signal_short = pd.Series(0, index=series.index) # Series of 0s with all days 
        signal_short[series==-1] = 1 # Fill in 1s where original series is -1
        signal_short = clear_signals(signal_short, lookahead_days) # Remove excess signals 
        
        # Where,
        # signal_long is 0 and signal_short is 1, filtered_signal is -1
        # signal_long is 1 and signal_short is 0, filtered_signal is 1
        # 
        # Note: 
        # - It's impossible for signal_long and signal_short to both be 1
        # - When they're both 0 it's trivial 
        filtered_signal[:][column] = signal_long - signal_short
    
    return filtered_signal


project_tests.test_filter_signals(filter_signals)
Tests Passed

View Data

Let's view the same chart as before, but with the redundant signals removed.

In [19]:
signal_5 = filter_signals(signal, 5)
signal_10 = filter_signals(signal, 10)
signal_20 = filter_signals(signal, 20)
In [20]:
signal_5.head()
Out[20]:
ticker A AAL AAP AAPL ABBV ABC ABT ACN ADBE ADI ... XL XLNX XOM XRAY XRX XYL YUM ZBH ZION ZTS
date
2013-07-01 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
2013-07-02 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
2013-07-03 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
2013-07-05 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
2013-07-08 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0

5 rows × 519 columns

In [21]:
for signal_data, signal_days in [(signal_5, 5), (signal_10, 10), (signal_20, 20)]:
    project_helper.plot_signal(
        close[apple_ticker],
        signal_data[apple_ticker],
        'Long and Short of {} Stock with {} day signal window'.format(apple_ticker, signal_days))

Lookahead Close Prices

With the trading signal done, we can start working on evaluating how many days to short or long the stocks. In this problem, implement get_lookahead_prices to get the close price days ahead in time. You can get the number of days from the variable lookahead_days. We'll use the lookahead prices to calculate future returns in another problem.

In [22]:
def get_lookahead_prices(close, lookahead_days):
    """
    Get the lookahead prices for `lookahead_days` number of days.
    
    Parameters
    ----------
    close : DataFrame
        Close price for each ticker and date
    lookahead_days : int
        The number of days to look ahead
    
    Returns
    -------
    lookahead_prices : DataFrame
        The lookahead prices for each ticker and date
    """
    
    # TODO: Implement function
    lookahead_prices = close.shift(-lookahead_days)
    
    return lookahead_prices


project_tests.test_get_lookahead_prices(get_lookahead_prices)
Tests Passed

View Data

Using the get_lookahead_prices function, let's generate lookahead closing prices for 5, 10, and 20 days.

Let's also chart a subsection of a few months of the Apple stock instead of years. This will allow you to view the differences between the 5, 10, and 20 day lookaheads. Otherwise, they will mesh together when looking at a chart that is zoomed out.

In [23]:
lookahead_5_price = get_lookahead_prices(close, 5)
lookahead_10_price = get_lookahead_prices(close, 10)
lookahead_20_price = get_lookahead_prices(close, 20)
In [24]:
close.head(6) # Note: AAPL at index 6 is 54.81320389
Out[24]:
ticker A AAL AAP AAPL ABBV ABC ABT ACN ADBE ADI ... XL XLNX XOM XRAY XRX XYL YUM ZBH ZION ZTS
date
2013-07-01 29.99418563 16.17609308 81.13821681 53.10917319 34.92447839 50.86319750 31.42538772 64.69409505 46.23500000 39.91336014 ... 27.66879066 35.28892781 76.32080247 40.02387348 22.10666494 25.75338607 45.48038323 71.89882693 27.85858718 29.44789315
2013-07-02 29.65013670 15.81983388 80.72207258 54.31224742 35.42807578 50.69676639 31.27288084 64.71204071 46.03000000 39.86057632 ... 27.54228410 35.05903252 76.60816761 39.96552964 22.08273998 25.61367511 45.40266113 72.93417195 28.03893238 28.57244125
2013-07-03 29.70518453 16.12794994 81.23729877 54.61204262 35.44486235 50.93716689 30.72565028 65.21451912 46.42000000 40.18607651 ... 27.33445191 35.28008569 76.65042719 40.00442554 22.20236479 25.73475794 46.06329899 72.30145844 28.18131017 28.16838652
2013-07-05 30.43456826 16.21460758 81.82188233 54.17338125 35.85613355 51.37173702 31.32670680 66.07591068 47.00000000 40.65233352 ... 27.69589920 35.80177117 77.39419581 40.67537968 22.58516418 26.06075017 46.41304845 73.16424628 29.39626730 29.02459772
2013-07-08 30.52402098 16.31089385 82.95141667 53.86579916 36.66188936 52.03746147 31.76628544 66.82065546 46.62500000 40.25645492 ... 27.98505704 35.20050655 77.96892611 40.64620776 22.48946433 26.22840332 46.95062632 73.89282298 29.57661249 29.76536472
2013-07-09 30.68916447 16.71529618 82.43619048 54.81320389 36.35973093 51.69535307 31.16522893 66.48866080 47.26000000 40.69632003 ... 28.31939579 35.50113886 78.89018496 40.80179133 22.48946433 26.58233774 47.28094525 73.70108798 28.91218282 29.80384612

6 rows × 519 columns

In [25]:
lookahead_5_price.head() # Note: AAPL at index 1 is 54.81320389
Out[25]:
ticker A AAL AAP AAPL ABBV ABC ABT ACN ADBE ADI ... XL XLNX XOM XRAY XRX XYL YUM ZBH ZION ZTS
date
2013-07-01 30.68916447 16.71529618 82.43619048 54.81320389 36.35973093 51.69535307 31.16522893 66.48866080 47.26000000 40.69632003 ... 28.31939579 35.50113886 78.89018496 40.80179133 22.48946433 26.58233774 47.28094525 73.70108798 28.91218282 29.80384612
2013-07-02 31.17771395 16.53235227 81.99032166 54.60295791 36.85493502 52.28710814 31.16522893 66.71298151 47.25000000 41.10979324 ... 27.95794850 36.39419366 78.45068533 40.71427558 22.96796358 26.98284247 47.08340158 74.00785631 28.32368796 29.86156823
2013-07-03 31.45983407 16.72492481 82.00022986 55.45406479 37.08155384 53.72026495 31.85599537 67.47567196 47.99000000 42.22705062 ... 28.50011944 37.00430040 78.83102155 41.01571874 23.23113816 27.03872686 46.54333492 74.93774876 27.84909533 29.74612402
2013-07-05 31.48047700 16.90786872 81.91105609 55.35309481 38.15724076 53.98840397 31.81096287 67.76280247 48.39000000 42.53495620 ... 28.92482002 38.00346072 78.94089646 40.83096325 23.49431274 27.08529718 45.96422730 75.68549560 28.44708204 30.15979909
2013-07-08 31.72819223 17.10044125 82.61453801 55.47379158 37.79303181 53.84971137 31.95506689 68.41781897 48.12000000 42.57894271 ... 29.27723113 38.17146113 78.81411772 40.84068723 23.54216266 27.06666905 46.69299195 76.27027369 28.77929688 30.38106716

5 rows × 519 columns

In [26]:
project_helper.plot_lookahead_prices(
    close[apple_ticker].iloc[150:250],
    [
        (lookahead_5_price[apple_ticker].iloc[150:250], 5),
        (lookahead_10_price[apple_ticker].iloc[150:250], 10),
        (lookahead_20_price[apple_ticker].iloc[150:250], 20)],
    '5, 10, and 20 day Lookahead Prices for Slice of {} Stock'.format(apple_ticker))

Lookahead Price Returns

Implement get_return_lookahead to generate the log price return between the closing price and the lookahead price.

In [27]:
def get_return_lookahead(close, lookahead_prices):
    """
    Calculate the log returns from the lookahead days to the signal day.
    
    Parameters
    ----------
    close : DataFrame
        Close price for each ticker and date
    lookahead_prices : DataFrame
        The lookahead prices for each ticker and date
    
    Returns
    -------
    lookahead_returns : DataFrame
        The lookahead log returns for each ticker and date
    """
    
    # TODO: Implement function
    lookahead_returns = np.log(lookahead_prices) - np.log(close)
    
    return lookahead_returns


project_tests.test_get_return_lookahead(get_return_lookahead)
Tests Passed

View Data

Using the same lookahead prices and same subsection of the Apple stock from the previous problem, we'll view the lookahead returns.

In order to view price returns on the same chart as the stock, a second y-axis will be added. When viewing this chart, the axis for the price of the stock will be on the left side, like previous charts. The axis for price returns will be located on the right side.

In [30]:
price_return_5 = get_return_lookahead(close, lookahead_5_price)
price_return_10 = get_return_lookahead(close, lookahead_10_price)
price_return_20 = get_return_lookahead(close, lookahead_20_price)
In [31]:
price_return_5.head()
Out[31]:
ticker A AAL AAP AAPL ABBV ABC ABT ACN ADBE ADI ... XL XLNX XOM XRAY XRX XYL YUM ZBH ZION ZTS
date
2013-07-01 0.02290609 0.03278982 0.01587046 0.03158145 0.04027390 0.01622827 -0.00831308 0.02736149 0.02192718 0.01942656 ... 0.02324185 0.00599552 0.03311128 0.01924987 0.01716780 0.03168088 0.03882627 0.02475761 0.03712180 0.01201508
2013-07-02 0.05023681 0.04405474 0.01558916 0.00533830 0.03948492 0.03088771 -0.00344828 0.03045227 0.02615930 0.03085860 ... 0.01497911 0.03737596 0.02376652 0.01856146 0.03930405 0.05207481 0.03634981 0.01461397 0.01010450 0.04412965
2013-07-03 0.05739003 0.03634632 0.00934756 0.01530060 0.04514133 0.05319745 0.03612778 0.03408499 0.03326226 0.04954045 ... 0.04176040 0.04771547 0.02805142 0.02496529 0.04529474 0.04942764 0.01036730 0.03581345 -0.01185852 0.05449853
2013-07-05 0.03378850 0.04186658 0.00108926 0.02154290 0.06220090 0.04968112 0.01533999 0.02520917 0.02914558 0.04527000 ... 0.04341569 0.05967986 0.01978764 0.00381771 0.03946514 0.03856068 -0.00971721 0.03387968 -0.03282211 0.03836621
2013-07-08 0.03869168 0.04727105 -0.00406943 0.02941493 0.03038696 0.03423317 0.00592524 0.02362106 0.03156101 0.05608947 ... 0.04513943 0.08102767 0.01078178 0.00477328 0.04574602 0.03146013 -0.00550246 0.03166756 -0.02732766 0.02047416

5 rows × 519 columns

In [32]:
price_return_5.tail(7)
Out[32]:
ticker A AAL AAP AAPL ABBV ABC ABT ACN ADBE ADI ... XL XLNX XOM XRAY XRX XYL YUM ZBH ZION ZTS
date
2017-06-22 -0.02807566 0.01318611 -0.03928700 -0.01348055 -0.00961150 -0.00634989 -0.01102052 0.00742648 -0.01719763 -0.04502206 ... 0.01990685 -0.03671260 -0.00469775 0.01224703 0.04879183 0.01931094 -0.01473099 -0.01166058 0.03917525 -0.01603082
2017-06-23 -0.00548356 0.03416199 -0.02665922 -0.01557041 -0.00179125 -0.01355419 -0.00962235 0.00762929 -0.02768174 -0.04707490 ... 0.00894399 -0.04870132 -0.01084155 0.01688284 0.01864438 0.02004440 -0.01426865 -0.00535944 0.04614052 -0.00639184
2017-06-26 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan
2017-06-27 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan
2017-06-28 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan
2017-06-29 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan
2017-06-30 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan

7 rows × 519 columns

In [33]:
project_helper.plot_price_returns(
    close[apple_ticker].iloc[150:250],
    [
        (price_return_5[apple_ticker].iloc[150:250], 5),
        (price_return_10[apple_ticker].iloc[150:250], 10),
        (price_return_20[apple_ticker].iloc[150:250], 20)],
    '5, 10, and 20 day Lookahead Returns for Slice {} Stock'.format(apple_ticker))

Compute the Signal Return

Using the price returns generate the signal returns.

In [34]:
def get_signal_return(signal, lookahead_returns):
    """
    Compute the signal returns.
    
    Parameters
    ----------
    signal : DataFrame
        The long, short, and do nothing signals for each ticker and date
    lookahead_returns : DataFrame
        The lookahead log returns for each ticker and date
    
    Returns
    -------
    signal_return : DataFrame
        Signal returns for each ticker and date
    """
    
    # TODO: Implement function
    
    # Note: 
    #     Signal = 1 means buy/long
    #     Signal = -1 means sell/short
    signal_return = signal*lookahead_returns 
    
    return signal_return


project_tests.test_get_signal_return(get_signal_return)
Tests Passed

View Data

Let's continue using the previous lookahead prices to view the signal returns. Just like before, the axis for the signal returns is on the right side of the chart.

In [35]:
signal_return_5 = get_signal_return(signal_5, price_return_5)
signal_return_10 = get_signal_return(signal_10, price_return_10)
signal_return_20 = get_signal_return(signal_20, price_return_20)
In [36]:
signal_return_5.head()
Out[36]:
ticker A AAL AAP AAPL ABBV ABC ABT ACN ADBE ADI ... XL XLNX XOM XRAY XRX XYL YUM ZBH ZION ZTS
date
2013-07-01 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 -0.00000000 0.00000000 0.00000000 0.00000000 ... 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
2013-07-02 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 -0.00000000 0.00000000 0.00000000 0.00000000 ... 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
2013-07-03 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 ... 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 -0.00000000 0.00000000
2013-07-05 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 ... 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 -0.00000000 0.00000000 -0.00000000 0.00000000
2013-07-08 0.00000000 0.00000000 -0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 ... 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 -0.00000000 0.00000000 -0.00000000 0.00000000

5 rows × 519 columns

In [37]:
signal_return_5.tail(7)
Out[37]:
ticker A AAL AAP AAPL ABBV ABC ABT ACN ADBE ADI ... XL XLNX XOM XRAY XRX XYL YUM ZBH ZION ZTS
date
2017-06-22 -0.00000000 0.00000000 -0.00000000 -0.00000000 -0.00961150 -0.00634989 -0.00000000 0.00000000 -0.00000000 -0.00000000 ... 0.00000000 -0.00000000 -0.00000000 0.00000000 0.00000000 0.00000000 -0.00000000 -0.00000000 0.00000000 -0.00000000
2017-06-23 -0.00000000 0.00000000 -0.00000000 -0.00000000 -0.00000000 -0.00000000 -0.00000000 0.00000000 -0.00000000 -0.00000000 ... 0.00000000 -0.00000000 -0.00000000 0.00000000 0.00000000 0.00000000 -0.00000000 -0.00000000 0.00000000 -0.00000000
2017-06-26 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan
2017-06-27 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan
2017-06-28 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan
2017-06-29 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan
2017-06-30 nan nan nan nan nan nan nan nan nan nan ... nan nan nan nan nan nan nan nan nan nan

7 rows × 519 columns

In [38]:
title_string = '{} day Lookahead Signal Returns for {} Stock'
project_helper.plot_signal_returns(
    close[apple_ticker],
    [
        (signal_return_5[apple_ticker], signal_5[apple_ticker], 5),
        (signal_return_10[apple_ticker], signal_10[apple_ticker], 10),
        (signal_return_20[apple_ticker], signal_20[apple_ticker], 20)],
    [title_string.format(5, apple_ticker), title_string.format(10, apple_ticker), title_string.format(20, apple_ticker)])

Test for Significance

Histogram

Let's plot a histogram of the signal return values.

In [39]:
project_helper.plot_signal_histograms(
    [signal_return_5, signal_return_10, signal_return_20],
    'Signal Return',
    ('5 Days', '10 Days', '20 Days'))

Question: What do the histograms tell you about the signal returns?

None of the histograms of the signal returns have a normal distribution. As the lookahead period increases, the distribution gets increasingly less normal. (We can see a slight lump on the right side of the distribution emerge at 20 days, and a smaller one at 10 days)

Outliers

You might have noticed the outliers in the 10 and 20 day histograms. To better visualize the outliers, let's compare the 5, 10, and 20 day signals returns to normal distributions with the same mean and deviation for each signal return distributions.

In [40]:
project_helper.plot_signal_to_normal_histograms(
    [signal_return_5, signal_return_10, signal_return_20],
    'Signal Return',
    ('5 Days', '10 Days', '20 Days'))

Kolmogorov-Smirnov Test

While you can see the outliers in the histogram, we need to find the stocks that are causing these outlying returns. We'll use the Kolmogorov-Smirnov Test or KS-Test. This test will be applied to teach ticker's signal returns where a long or short signal exits.

In [41]:
# Filter out returns that don't have a long or short signal.
long_short_signal_returns_5 = signal_return_5[signal_5 != 0].stack()
long_short_signal_returns_10 = signal_return_10[signal_10 != 0].stack()
long_short_signal_returns_20 = signal_return_20[signal_20 != 0].stack()

# Get just ticker and signal return
long_short_signal_returns_5 = long_short_signal_returns_5.reset_index().iloc[:, [1,2]]
long_short_signal_returns_5.columns = ['ticker', 'signal_return']
long_short_signal_returns_10 = long_short_signal_returns_10.reset_index().iloc[:, [1,2]]
long_short_signal_returns_10.columns = ['ticker', 'signal_return']
long_short_signal_returns_20 = long_short_signal_returns_20.reset_index().iloc[:, [1,2]]
long_short_signal_returns_20.columns = ['ticker', 'signal_return']

# View some of the data
long_short_signal_returns_5.head(10)
Out[41]:
ticker signal_return
0 A 0.00732604
1 ABC 0.01639650
2 ADP 0.00981520
3 AGENEN 0.01091548
4 AKAM 0.04400495
5 ALGN 0.01545561
6 APC 0.00305859
7 ARMENA 0.02839261
8 BA 0.08061297
9 BAKERI 0.01513002

This gives you the data to use in the KS-Test.

Now it's time to implement the function calculate_kstest to use Kolmogorov-Smirnov test (KS test) between a distribution of stock returns (the input dataframe in this case) and each stock's signal returns. Run KS test on a normal distribution against each stock's signal returns. Use scipy.stats.kstest perform the KS test. When calculating the standard deviation of the signal returns, make sure to set the delta degrees of freedom to 0.

For this function, we don't reccommend you try to find a vectorized solution. Instead, you should iterate over the groupby function.

In [42]:
from scipy.stats import kstest


def calculate_kstest(long_short_signal_returns):
    """
    Calculate the KS-Test against the signal returns with a long or short signal.
    
    Parameters
    ----------
    long_short_signal_returns : DataFrame
        The signal returns which have a signal.
        This DataFrame contains two columns, "ticker" and "signal_return"
    
    Returns
    -------
    ks_values : Pandas Series
        KS static for all the tickers
    p_values : Pandas Series
        P value for all the tickers
    """
    #TODO: Implement function
    
    ks_values = pd.Series()
    p_values = pd.Series()
    
    mean = long_short_signal_returns['signal_return'].mean()
    std = long_short_signal_returns['signal_return'].std(ddof = 0)
    
    groups = long_short_signal_returns.groupby('ticker')
    
    for name, group in groups:
        k, p = kstest(rvs=group['signal_return'], cdf='norm', args = (mean,std))
        ks_values[name] = k
        p_values[name] = p
        
    return ks_values, p_values


project_tests.test_calculate_kstest(calculate_kstest)
Tests Passed

View Data

Using the signal returns we created above, let's calculate the ks and p values.

In [43]:
ks_values_5, p_values_5 = calculate_kstest(long_short_signal_returns_5)
ks_values_10, p_values_10 = calculate_kstest(long_short_signal_returns_10)
ks_values_20, p_values_20 = calculate_kstest(long_short_signal_returns_20)

print('ks_values_5:\n{}'.format(ks_values_5.head(10)))
print('\np_values_5:\n{}'.format(p_values_5.head(10)))
ks_values_5:
A      0.17228787
AAL    0.10739184
AAP    0.19711229
AAPL   0.15564360
ABBV   0.16832121
ABC    0.21417391
ABT    0.21388708
ACN    0.28237106
ADBE   0.24283428
ADI    0.19444271
dtype: float64

p_values_5:
A      0.18636278
AAL    0.72506723
AAP    0.04476594
AAPL   0.24721966
ABBV   0.24590112
ABC    0.02727191
ABT    0.04803981
ACN    0.00581795
ADBE   0.00906186
ADI    0.09841955
dtype: float64

Find Outliers

With the ks and p values calculated, let's find which symbols are the outliers. Implement the find_outliers function to find the following outliers:

  • Symbols that pass the null hypothesis with a p-value less than pvalue_threshold.
  • Symbols that with a KS value above ks_threshold.
In [44]:
def find_outliers(ks_values, p_values, ks_threshold, pvalue_threshold=0.05):
    """
    Find outlying symbols using KS values and P-values
    
    Parameters
    ----------
    ks_values : Pandas Series
        KS static for all the tickers
    p_values : Pandas Series
        P value for all the tickers
    ks_threshold : float
        The threshold for the KS statistic
    pvalue_threshold : float
        The threshold for the p-value
    
    Returns
    -------
    outliers : set of str
        Symbols that are outliers
    """
    
    # TODO: Implement function
    outliers = set()
    
    # Loop over values 
    for x in range(ks_values.shape[0]):
        
        # Check each value if it's an outlier 
        if(ks_values.iloc[x] > ks_threshold and p_values.iloc[x] < pvalue_threshold):
            outliers.add(ks_values.index[x])
    
    # WRONG 
    # outliers_ks = ks_values.index[ks_values > ks_threshold]
    # outliers_p = p_values.index[p_values > pvalue_threshold]
    
    return outliers


project_tests.test_find_outliers(find_outliers)
Tests Passed

View Data

Using the find_outliers function you implemented, let's see what we found.

In [45]:
ks_threshold = 0.8
outliers_5 = find_outliers(ks_values_5, p_values_5, ks_threshold)
outliers_10 = find_outliers(ks_values_10, p_values_10, ks_threshold)
outliers_20 = find_outliers(ks_values_20, p_values_20, ks_threshold)

outlier_tickers = outliers_5.union(outliers_10).union(outliers_20)
print('{} Outliers Found:\n{}'.format(len(outlier_tickers), ', '.join(list(outlier_tickers))))
24 Outliers Found:
SAXATI, SYLVES, VVEDEN, TURKES, LINIFO, PULCHE, ARMENA, GREIGI, URUMIE, BAKERI, SCHREN, CLUSIA, SPRENG, HUMILI, KOLPAK, KAUFMA, GESNER, AGENEN, ALTAIC, DASYST, PRAEST, TARDA, ORPHAN, BIFLOR

Show Significance without Outliers

Let's compare the 5, 10, and 20 day signals returns without outliers to normal distributions. Also, let's see how the P-Value has changed with the outliers removed.

In [46]:
good_tickers = list(set(close.columns) - outlier_tickers)

project_helper.plot_signal_to_normal_histograms(
    [signal_return_5[good_tickers], signal_return_10[good_tickers], signal_return_20[good_tickers]],
    'Signal Return Without Outliers',
    ('5 Days', '10 Days', '20 Days'))

That's more like it! The returns are closer to a normal distribution. You have finished the research phase of a Breakout Strategy. You can now submit your project.

Submission

Now that you're done with the project, it's time to submit it. Click the submit button in the bottom right. One of our reviewers will give you feedback on your project with a pass or not passed grade. You can continue to the next section while you wait for feedback.